package com.remoter.configure.yaml;

import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.yaml.snakeyaml.Yaml;

import com.remoter.basic.configure.support.AbstractConfiguration;
import com.remoter.basic.util.ServiceLoader.MetaName;
import com.remoter.basic.util.StringUtil;

/**
 * @author			koko
 * @date 			2017-08-09 15:39:52
 * @description 	类功能说明
 */
@MetaName("yaml")
public class YamlConfiguration extends AbstractConfiguration{
	
	private static final LinkedHashMap<String,String> maps = new LinkedHashMap<String,String>();
	
	@SuppressWarnings("unchecked")
	public YamlConfiguration(){
		String path = this.getConfigFile();
		try(
			InputStream inputStream = this.getClass().getResourceAsStream(path);
		){
			Yaml yaml = new Yaml();
			maps.putAll(yaml.loadAs(inputStream,LinkedHashMap.class));
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}
		if(logger.isDebugEnabled()){
			for(Entry<String,String> entry : maps.entrySet()){
				logger.debug(String.format("load config [%s=%s]",entry.getKey(),entry.getValue()));
			}
		}
	}
	
	@Override
	protected String getValue(String name){
		if(StringUtil.isBlank(name)){
			return null;
		}
		String result = null;
		String[] names = null;
		if(name.indexOf(".")>0){
			names = name.split("\\.");
		}else{
			names = new String[]{name};
		}
		if(null != names && names.length > 0){
			Map<?,?> temp = maps;
			for(int i=0;i<names.length;i++){
				String n = names[i];
				if(i == names.length - 1){
					result = temp.get(n).toString();
				}else{
					if(!temp.containsKey(n)){
						break;
					}
					temp = (Map<?,?>)temp.get(n);
				}
			}
		}
		return result;
	}
	
}